

from util import ReadFile, WriteFile
from xyztools import extractXYZLine

import datetime

def nrnConcatenateXYZS( srcFilename1, srcFilename2, sinkFilename):
    datestr = datetime.datetime.now().strftime("%d-%B-%Y")
    print " -- Concatentating Files"
    
    D1 = ReadFile(srcFilename1)
    D2 = ReadFile(srcFilename2)

    dataLines1 = [l for l in D1.split("\n") if l.strip() and not l.strip().startswith("#") ]
    dataLines2 = [l for l in D2.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines1 = [l for l in D1.split("\n") if l.strip() and l.strip().startswith("#") ]
    CommentLines2 = [l for l in D2.split("\n") if l.strip() and l.strip().startswith("#") ]

	
    
    # copies comment lines and adds comment line showing the processing that's been done plus date.
    #outData = [ "#Comment From File1: %s"%srcFilename1 ] + CommentLines1 + [	"#Comment From File2: %s"%srcFilename2 ] + CommentLines2 + ["# Files Concatenated by nrnConcatenate.py" + " on: %s"%datestr]
    outData = CommentLines1 + CommentLines2 + ["# Files Concatenated by nrnConcatenate.py" + " on: %s"%datestr] 
    # Remap the id's
    # Write Datafile 1
    idMap = {}
    for l in dataLines1:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
        
        new_id = len(idMap) + 1
        new_p = p if p ==-1 else idMap[ (0,p) ]
        
        outData.append( "\t".join( [str(g) for g in [new_id,t,x,y,z,X,Y,Z,new_p] ] ) ) 
        idMap[ (0,i) ] = new_id
    
    
    #print srcFilename2
    # Write Datafile 2
    for l in dataLines2:
        #print l
        #print 
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)
        
        new_id = len(idMap) + 1
        
        #print p
        new_p = p if p ==-1 else idMap[(1,p)]
        
        outData.append( "\t".join( [str(g) for g in [new_id,t,x,y,z,X,Y,Z,new_p] ] ) ) 
        idMap[(1,i)] = new_id
        
    WriteFile( sinkFilename, "\n".join( outData) )
    
